<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>CacheCloud应用列表</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />
    <#include '/inc/frontResources.html'>
  </head>

  <body class="hold-transition sidebar-mini layout-navbar-fixed">
    <div class="wrapper">
      <!-- Header End -->
      <#include "/inc/head.html">
      <div class="content-wrapper ml-0">
        <div class="content">
          <div class="">
            <!--<div class="card">
              <div class="card-body">-->
                <!-- stat info start -->
                <div class="container-fluid">
                  <div class="row">
                    <div class="col-lg-4">
                      <div class="card" id="memDiv" style="display: none">
                        <div class="card-header">
                          <h3 class="card-title">应用统计</h3>
                        </div>
                        <div class="card-body">
                          <table class="table table-striped table-hover">
                            <tbody>
                            <tr>
                              <td>总应用数</td>
                              <td id="appCount"></td>
                              <td>主节点数</td>
                              <td id="masterInsCount"></td>
                            </tr>
                            <tr>
                              <td>申请内存</td>
                              <td id="applyMem"></td>
                              <td>内存使用率</td>
                              <td id="memUsedRatio"></td>
                            </tr>
                            </tbody>
                          </table>

                          <div class="row">
                            <div class="col-lg-12">
                              <div id="memChart" style="min-height: 300px;" class="echart"></div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div class="col-lg-4">
                      <div class="card" id="monitorDiv" style="display: none">
                        <div class="card-header">
                          <h3 class="card-title">监控统计</h3>
                        </div>
                        <div class="card-body">
                          <table class="table table-striped table-hover">
                            <tbody>
                            <tr>
                              <td>总异常数</td>
                              <td id="excpCount"></td>
                              <td>慢查询数</td>
                              <td id="slowCount"></td>
                            </tr>
                            <tr>
                              <td>延迟事件数</td>
                              <td id="latencyCount"></td>
                              <td>命令调用数</td>
                              <td id="cmdCount"></td>
                            </tr>
                            </tbody>
                          </table>

                          <div class="row">
                            <div class="col-lg-12">
                              <div id="monitorChart" style="min-height: 300px;" class="echart"></div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div class="col-lg-4">
                      <div class="card" id="auditDiv" style="display: none">
                        <div class="card-header">
                          <h3 class="card-title">内存审计top5</h3>
                        </div>
                        <div class="card-body">
                          <table class="table table-striped table-hover">
                            <tbody>
                            <tr>
                              <td>请合理配置应用资源</td>
                            </tr>
                            <tr>
                              <td>展示内存使用率最低的前5个应用</td>
                            </tr>
                            </tbody>
                          </table>
                          <div class="row">
                            <div class="col-lg-12">
                              <div id="auditChart" style="min-height: 300px;" class="echart"></div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                </div>
           <!--   </div>
            </div>-->
          </div>

          <div class="container-fluid">
            <!-- stat info End -->
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">应用列表</h3>
              </div>
              <#if currentUser?? && currentUser.type?? && currentUser.type == 0>
                <div class="card-body">
                  <!-- form begin -->
                  <div class="">
                    <form class="row align-items-center" role="form" method="post" action="${request.contextPath}/admin/app/list" id="appList" name="ec">
                      <div class="col-auto">
                        <select id="bizId" name="bizId" class="selectpicker w-100 border rounded" data-live-search="true">
                          <option value="-1">业务组</option>
                          <#list bizList as biz>
                            <option value="${biz.id}" <#if appSearch.bizId?? && biz.id == appSearch.bizId>selected</#if>>${biz.name}</option>
                          </#list>
                        </select>
                      </div>
                      <div class="col-auto">
                        <select id="userId" name="userId" class="selectpicker w-100 border rounded" data-live-search="true">
                          <option value="-1">用户</option>
                          <#list userList as userInfo>
                            <option value="${userInfo.id}" <#if (appSearch.userId?? && userInfo.id == appSearch.userId)>selected</#if>>${userInfo.chName}(${userInfo.name})</option>
                          </#list>
                        </select>
                      </div>
                      <div class="col-md-2">
                        <input type="text" class="form-control" id="appParam" name="appParam" value="${appParam!}" placeholder="应用ID/应用名">
                      </div>
                      <div class="col-auto">
                        <select name="versionId" id="versionId" class="form-select select2_category">
                          <option value="">Redis版本</option>
                          <#list resourcelist as version>
                          <option value="${version.id}" <#if appSearch.versionId?? && version.id == appSearch.versionId>selected</#if>>${version.name}</option>
                        </#list>
                        </select>
                      </div>
                      <div class="col-auto">
                        <select name="appType" class="form-select w-100">
                          <option value="">
                            全部类型
                          </option>
                          <option value="2" <#if appSearch.appType?? && appSearch.appType == 2>selected</#if>>
                          Redis-Cluster
                          </option>
                          <option value="5" <#if appSearch.appType?? && appSearch.appType == 5>selected</#if>>
                          Redis-Sentinel
                          </option>
                          <option value="6" <#if appSearch.appType?? && appSearch.appType == 6>selected</#if>>
                          Redis-Standalone
                          </option>
                        </select>
                      </div>
                      <div class="col-auto">
                        <select name="appStatus" class="form-select w-100">
                          <option value="-1">
                            全部状态
                          </option>
                          <option value="0" <#if appSearch.appStatus?? && appSearch.appStatus == 0>selected</#if>>
                          未分配
                          </option>
                          <option value="1" <#if appSearch.appStatus?? && appSearch.appStatus == 1>selected</#if>>
                          申请中
                          </option>
                          <option value="2" <#if appSearch.appStatus?? && appSearch.appStatus == 2>selected</#if>>
                          运行中
                          </option>
                          <option value="3" <#if appSearch.appStatus?? && appSearch.appStatus == 3>selected</#if>>
                          已下线
                          </option>
                          <option value="4" <#if appSearch.appStatus?? && appSearch.appStatus == 4>selected</#if>>
                          驳回
                          </option>
                        </select>
                      </div>
                      <div class="col-auto">
                        <select name="pageSize" class="form-select w-100">
                          <option value="10" <#if page.pageSize?? && page.pageSize == 10>selected</#if>>
                          10行
                          </option>
                          <option value="20" <#if page.pageSize?? && page.pageSize == 20>selected</#if>>
                          20行
                          </option>
                          <option value="50" <#if page.pageSize?? && page.pageSize == 50>selected</#if>>
                          50行
                          </option>
                          <option value="100" <#if page.pageSize?? && page.pageSize == 100>selected</#if>>
                          100行
                          </option>
                        </select>
                      </div>
                      <input type="hidden" name="pageNo" id="pageNo">
                      <button type="submit" class="btn btn-primary col-auto">查询</button>
                    </form>
                  </div>
                  <!-- form end -->
                </div>
              </#if>

              <div class="card-body table-responsive">
                <!-- table begin -->
                <table class="table table-striped table-hover table-sm border-top border-bottom" style="white-space: nowrap">
                  <thead>
                      <th scope="col">应用ID</td>
                      <th scope="col">应用名</td>
                      <th scope="col">环境</td>
                      <th scope="col">版本</td>
                      <th scope="col">应用类型</td>
                      <th scope="col">空间详情</td>
                      <th scope="col">命中率</td>
                      <th scope="col">已运行时间</td>
                  </thead>
                  <tbody>
                  <#list appDetailList as appDetail>
                    <tr>
                      <th scope="row">
                        <#if appDetail.appDesc.status == 0 || appDetail.appDesc.status == 1>
                          ${appDetail.appDesc.appId}
                        <#elseif appDetail.appDesc.status == 2 || appDetail.appDesc.status == 3 || appDetail.appDesc.status == 4>
                          <a title="${appDetail.appDesc.intro}" target="_blank" href="${request.contextPath}/admin/app/index?appId=${appDetail.appDesc.appId}">${appDetail.appDesc.appId}</a>
                        </#if>
                      </th>
                      <td>
                        <#if appDetail.appDesc.status == 0 || appDetail.appDesc.status == 1>
                            ${appDetail.appDesc.name}
                        <#elseif appDetail.appDesc.status == 2 || appDetail.appDesc.status == 3 || appDetail.appDesc.status == 4>
                          <a target="_blank" href="${request.contextPath}/admin/app/index?appId=${appDetail.appDesc.appId}">${appDetail.appDesc.name}</a>
                        </#if>
                      </td>
                      <td>
                        <#if appDetail.appDesc.isTest == 2>
                          试用
                        <#elseif appDetail.appDesc.isTest == 1>
                          测试
                        <#elseif appDetail.appDesc.isTest == 0>
                          正式
                        </#if>
                      </td>
                      <td>
                        ${appDetail.appDesc.versionName?replace('redis-','')}
                      </td>
                      <td>${appDetail.appDesc.typeDesc!}</td>
                      <td>
                        <div class="progress progress-fs-1" role="progressbar" aria-valuenow="${appDetail.memUsePercent}" aria-valuemax="100"
                             aria-valuemin="0" >
                          <#if (appDetail.memUsePercent >= 80)>
                          <#assign progressBarStatus="bg-danger"/>
                          <#else>
                          <#assign progressBarStatus="bg-success"/>
                          </#if>
                          <div class="progress-bar ${progressBarStatus}"
                               style="width: ${appDetail.memUsePercent}%; overflow: visible;">
                            <span style="color: #000000; margin-bottom: 0">
                              ${(appDetail.mem * appDetail.memUsePercent / 100 / 1024)?string('#.##')}G&nbsp;&nbsp;Used / ${(appDetail.mem / 1024 * 1.0)?string('#.##')}G&nbsp;&nbsp;Total
                            </span>
                          </div>
                        </div>
                      </td>
                      <td>
                        <#if (appDetail.hitPercent <= 0)>
                        无
                        <#elseif (appDetail.hitPercent <= 30)>
                        <label class="badge bg-danger">${appDetail.hitPercent}%</label>
                        <#elseif (appDetail.hitPercent >= 30 && appDetail.hitPercent < 50)>
                        <label class="badge bg-warning">${appDetail.hitPercent}%</label>
                        <#elseif (appDetail.hitPercent >= 50 && appDetail.hitPercent < 90)>
                        <label class="badge bg-info">${appDetail.hitPercent}%</label>
                        <#else>
                        <label class="badge bg-success">${appDetail.hitPercent}%</label>
                        </#if>
                      </td>
                      <td>
                        <#if appDetail.appDesc.status == 0>
                        <font color="red">未分配</font>
                        <#elseif appDetail.appDesc.status == 1>
                        <font color="red">申请中</font>
                        <#elseif appDetail.appDesc.status == 2>
                          <#if (appDetail.appDesc.isTest == 2)>
                            <label style="color:orange">
                              ${(30-((.now?long) - (appDetail.appDesc.passedTime?long))/1000/60/60/24)?string("0.0")}天后到期
                            </label>
                          <#else>
                            <label style="color:yellowgreen">
                              ${appDetail.appDesc.appRunDays!}天
                            </label>
                          </#if>
                        <#elseif appDetail.appDesc.status == 3>
                        <font color="red">已下线</font>
                        <#elseif appDetail.appDesc.status == 4>
                        <font color="red">驳回</font>
                        </#if>
                      </td>
                    </tr>
                  </#list>
                  </tbody>
                </table>
                <!-- End Table with stripped rows -->
                <#if currentUser?? && currentUser.type?? && currentUser.type == 0>
                <div style="margin-bottom: 10px;">
                  <span>
                    <div id="pageDetail" style="float:left;padding-top:7px;color:#4A64A4;">
                      <#if page??>
                          共${page.totalPages!}页,${page.totalCount!}条
                      </#if>
                    </div>
                    <nav aria-label="Page navigation example" id="nav_navigation" class="d-inline-flex float-end">
                      <#include "/inc/page.html">
                    </nav>
                  </span>
                </div>
                </#if>
              </div>
            </div>
          </div>
        </div>
      </div>
      <#include "/inc/footer.html">
    </div>
  </body>
</html>
<script src="${request.contextPath}/assets/vendor/jquery/jquery-3.7.0.min.js"></script>
<script src="${request.contextPath}/assets/vendor/paginator/bootstrap-paginator.js"></script>
<script type="text/javascript">
  function searchJob(page){
    //form传参用pageSize
    document.getElementById("pageNo").value=page;
    document.getElementById("appList").submit();
  }

  function setAppStatisticOption(legendData, capacityData, versionData){
    var option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        data: legendData
      },
      series: [
        {
          name: '版本',
          type: 'pie',
          selectedMode: 'single',
          radius: [0, '30%'],
          label: {
            position: 'inner',
            fontSize: 14
          },
          labelLine: {
            show: false
          },
          data: versionData
        },
        {
          type: 'pie',
          radius: ['45%', '60%'],
          labelLine: {
            length: 20
          },
          label: {
            name: '内存',
            formatter: '{b|{b}：} \n{per|{d}%}  ',
            backgroundColor: '#F6F8FC',
            borderColor: '#8C8D8E',
            borderWidth: 1,
            borderRadius: 2,
            rich: {
              a: {
                color: '#6E7079',
                lineHeight: 22,
                align: 'center'
              },
              hr: {
                borderColor: '#8C8D8E',
                width: '100%',
                borderWidth: 1,
                height: 0
              },
              b: {
                color: '#4C5058',
                fontSize: 14,
                fontWeight: 'bold',
                lineHeight: 33
              },
              per: {
                color: '#fff',
                backgroundColor: '#4C5058',
                padding: [3, 4],
                borderRadius: 4
              }
            }
          },
          data: capacityData
        }
      ]
    };
    return option;
  }

  function initFigure(id, legendData, capacityData, versionData){
    echarts.init(document.querySelector("#" + id)).setOption(setAppStatisticOption(legendData, capacityData, versionData));
  };

  function setAppMonitorStatisticOption(dateData, slowLogData, excpData, latencyData){
    var option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['慢查询', '异常', '延迟事件']
      },
      grid: {
        left: '4%',
        right: '4%',
        bottom: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dateData
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '慢查询',
          type: 'line',
          smooth: true,
          data: slowLogData
        },
        {
          name: '异常',
          type: 'line',
          smooth: true,
          data: excpData
        },
        {
          name: '延迟事件',
          type: 'line',
          smooth: true,
          data: latencyData
        },
      ]
    };
    return option;
  }

  function initMonitorFigure(id, dateData, slowLogData, excpData, latencyData){
    echarts.init(document.querySelector("#" + id)).setOption(setAppMonitorStatisticOption(dateData, slowLogData, excpData, latencyData));
  };

  function setAppCapacityAuditOption(xData, data){
    var option = {
      title: {
        text: "内存审计top5"
      },
      tooltip: {
        trigger: 'axis',
        formatter: "{c} %"
      },
      xAxis: {
        type: 'category',
        data: xData
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: data,
          type: 'bar'
        }
      ]
    };
    return option;
  }

  function initAuditFigure(id, xData, data){
    echarts.init(document.querySelector("#" + id)).setOption(setAppCapacityAuditOption(xData, data));
  };

  $(document).ready(
          function () {
            var pieUrl = "${request.contextPath}/admin/app/listStats";
            $.ajax({
              type: "get",
              url: pieUrl,
              async: true,
              success: function (data) {
                console.log(data);
                // var data = eval("(" + data + ")");
                var capacityMap = data.capacityMap;
                var monitorList = data.monitorList;
                var appCount = capacityMap.appCount;
                var applyMem = capacityMap.applyMem;
                var usedMem = capacityMap.usedMem;
                var notUsedMem = capacityMap.notUsedMem;
                var masterCount = capacityMap.masterCount;
                var versionList = capacityMap.versionList;
                var auditList = capacityMap.auditList;
                var legendData = [
                        '使用内存-' + usedMem,
                        '未使用内存-' + notUsedMem
                ]
                var versionData = [];
                for(i = 0; i < versionList.length; i++){
                  versionData.push({
                      "value": versionList[i].value,
                      "name": versionList[i].key
                  });
                }
                var capacityData = [];
                capacityData.push({
                  "value": usedMem,
                  "name": "使用内存"
                });
                capacityData.push({
                  "value": notUsedMem,
                  "name": "未使用内存"
                });

                var memNum = new Number(applyMem/1024/1024/1024);
                var usedRatio = "0%";
                if(applyMem != 0){
                  var ratioNum = new Number(usedMem * 100/applyMem);
                  usedRatio = ratioNum.toFixed(2) + "%";
                }
                $("#appCount").text(appCount + "个");
                $("#masterInsCount").text(masterCount + "个");
                $("#applyMem").text(memNum.toFixed(2) + "G");
                $("#memUsedRatio").text(usedRatio);
                $("#memDiv").attr("style",  "display:'';");



                var excpCount = 0;
                var slowCount = 0;
                var latencyCount = 0;
                var cmdCount = 0;
                if(monitorList.length > 0){
                  var monitor = monitorList[monitorList.length - 1];
                  excpCount = monitor.connExpCount + monitor.cmdExpCount;
                  slowCount = monitor.slowLogCount;
                  latencyCount = monitor.latencyCount;
                  cmdCount = monitor.cmdCount;
                }
                $("#excpCount").html('<a href="#">' + excpCount + '</a>');
                $("#slowCount").html('<a href="#">' + slowCount + '</a>');
                $("#latencyCount").html('<a href="#">' + latencyCount + '</a>');
                $("#cmdCount").html('<a href="#">' + cmdCount + '</a>');
                $("#monitorDiv").attr("style",  "display:'';");

                $("#auditDiv").attr("style",  "display:'';");
                initFigure('memChart', legendData, capacityData, versionData);

                var dateData = [];
                var slowLogData = [];
                var excpData = [];
                var latencyData = [];
                for(i = 0; i < monitorList.length; i++){
                  var monitor = monitorList[i];
                  dateData.push(monitor.gatherTime);
                  slowLogData.push(monitor.slowLogCount);
                  excpData.push(monitor.connExpCount + monitor.cmdExpCount);
                  latencyData.push(monitor.latencyCount);
                }
                initMonitorFigure('monitorChart', dateData, slowLogData, excpData, latencyData);

                var xData = [];
                var auditData = [];
                var color = [
                  '#a90000',
                  '#0056ff',
                  '#bfx0b0',
                  '#ff6600',
                  '#ffac00'
                ];
                for(i = 0; i < auditList.length; i++){
                  var audit = auditList[i];
                  xData.push(audit.key);
                  auditData.push({
                    "value": audit.value,
                    "itemStyle" : {
                      "color": color[i]
                    }
                  })
                }

                initAuditFigure('auditChart', xData, auditData);
              }
            });
          });


</script>
